package com.hebxy.ssm.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hebxy.ssm.entity.Plan;
import com.hebxy.ssm.entity.User;
import com.hebxy.ssm.entity.jy1;
import com.hebxy.ssm.service.PlanService;
import com.hebxy.ssm.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;
	
	@Autowired
	private PlanService planService;
	
	@RequestMapping("/index")
	public String index(){
		return "user/index";
	}
	@RequestMapping("/login")
	public String Tologin(HttpServletRequest request){
		String str=(String) request.getSession().getAttribute("originalUrl");
		if(str!=null){
			return "main";
		}
		return "forward:/login.jsp";
		
	}
	@RequestMapping("/userLogin")
	public String login(@ModelAttribute("user") @Validated(value=jy1.class) User user,BindingResult r,HttpServletRequest request,ModelMap m){
		HttpSession session=request.getSession();
		if(r.hasErrors()){
			List<ObjectError> errors=r.getAllErrors();
			for(ObjectError o:errors){
				System.out.println(o.getDefaultMessage());
			}
			m.put("error", errors);
			return "forward:/login.jsp";
		}
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("card_number", user.getCard_number());
		map.put("password", user.getPassword());
		User user1=userService.findForlogin(map);
		if(user1!=null){
			String originalUrl =(String) session.getAttribute("originalUrl");
			
			session.setAttribute("username", user.getCard_number());
			System.out.println(originalUrl);
			if((originalUrl!=null&&!originalUrl.isEmpty())&&!originalUrl.equals("/login")&&!originalUrl.equals("/role**")){
				return "redirect:"+originalUrl;
			}
			return "main";
		}
		else{
			m.addAttribute("msg","卡号或者密码错误 请重新输入");
			return "forward:/login.jsp";
		}
		
	}
	@RequestMapping("/{page}")
	public String gotoAddUser(@PathVariable("page") String page,HttpServletRequest request){
		return "user/"+page;
	}
	
	@GetMapping("/userRegister")
	public String userRegister(ModelMap m){
		kaHaoHeTaoCan(m);
		return "/user/userRegister";
	}
	
	@PostMapping("/register")
	public String register(@ModelAttribute("user") @Validated User user,BindingResult r,ModelMap m){
		if(r.hasErrors()){
			List<ObjectError> errors = r.getAllErrors();
			for(ObjectError error:errors){
				System.out.println(error.getDefaultMessage());
			}
			m.put("msg", "校验不合格 注册用户失败");
			m.put("errors", errors);
			kaHaoHeTaoCan(m);
			return "user/userRegister";
		}
		Plan plan=planService.findPlanById(user.getPlan_id());
		if(user.getPrepaid_amount()<plan.getMonthly_fee()){
			m.put("msg2", "您预存的话费金额不足以支付本月固定套餐资费，请重新充值！");
			kaHaoHeTaoCan(m);
			return "user/userRegister";
		}
		user.setBalance(user.getPrepaid_amount()-plan.getMonthly_fee());
		userService.addUser(user);
		m.put("msg1", "注册成功，可以点击此处前往登录页面");
		m.put("card_number", user.getCard_number());
		m.put("taocan", planService.findPlanById(user.getPlan_id()));
		return "/user/userRegister";
		
	}
	//生成卡号
	public void kaHaoHeTaoCan(ModelMap m){
	List<String> card_numbers =new ArrayList<>();
	for(int i=0;i<10;i++){
		String numb="139";
		for(int j=0;j<8;j++){
			numb=numb+new Random().nextInt(10);
		}
		User user=userService.findByCardNumber(numb);
		if(user!=null){
			i=i-1;
		}else{
			System.out.println(numb);
			card_numbers.add(numb);
		}
	}
	m.addAttribute("card_numbers", card_numbers);
	
	List<Plan> plans= planService.findPlanAll();
	m.addAttribute("plans",plans );
	}

}
